package com.example.homework

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.homework.db.UserDBHelper

class GameActivity : AppCompatActivity() {
    private lateinit var gameView: GameView
    private lateinit var tvScore: TextView
    private lateinit var tvLevel: TextView
    private lateinit var username: String
    private lateinit var dbHelper: UserDBHelper
    private var isThreadRunning = true
    private lateinit var vibrator: Vibrator

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()
        setContentView(R.layout.activity_game)

        // 初始化震动器
        vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator

        // 初始化游戏数据
        username = intent.getStringExtra("username") ?: ""
        dbHelper = UserDBHelper(this)
        gameView = findViewById(R.id.game_view)
        tvScore = findViewById(R.id.tv_score)
        tvLevel = findViewById(R.id.tv_level)
        gameView.startGame()

        // 左方向键（带连续点击提速）
        val btnLeft = findViewById<Button>(R.id.btn_left)
        btnLeft.setOnClickListener {
            gameView.setDirection(GameView.LEFT)
            triggerVibration()
            handleSpeedUpByClick() // 处理连续点击提速
        }

        // 上方向键（带连续点击提速）
        val btnUp = findViewById<Button>(R.id.btn_up)
        btnUp.setOnClickListener {
            gameView.setDirection(GameView.UP)
            triggerVibration()
            handleSpeedUpByClick()
        }

        // 下方向键（带连续点击提速）
        val btnDown = findViewById<Button>(R.id.btn_down)
        btnDown.setOnClickListener {
            gameView.setDirection(GameView.DOWN)
            triggerVibration()
            handleSpeedUpByClick()
        }

        // 右方向键（带连续点击提速）
        val btnRight = findViewById<Button>(R.id.btn_right)
        btnRight.setOnClickListener {
            gameView.setDirection(GameView.RIGHT)
            triggerVibration()
            handleSpeedUpByClick()
        }

        // 游戏结束回调
        gameView.setGameListener(object : GameView.GameListener {
            override fun onGameOver(score: Int) {
                dbHelper.updateHighScore(username, score)
                val intent = Intent(this@GameActivity, ResultActivity::class.java).apply {
                    putExtra("username", username)
                    putExtra("score", score)
                }
                startActivity(intent)
                finish()
            }
        })

        // 分数更新线程
        Thread {
            while (isThreadRunning) {
                runOnUiThread {
                    tvScore.text = "分数：${gameView.getCurrentScore()}"
                    tvLevel.text = "等级：${gameView.getCurrentLevel()}"
                }
                try {
                    Thread.sleep(100)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

    // 连续点击提速处理
    private fun handleSpeedUpByClick() {
        val currentTime = System.currentTimeMillis()
        // 500ms内的连续点击触发提速
        if (currentTime - gameView.lastClickTime <= gameView.CLICK_INTERVAL) {
            gameView.clickCount++
            gameView.speedUpByClick() // 每次连续点击都提速
        } else {
            // 超过间隔重置计数器
            gameView.clickCount = 0
        }
        gameView.lastClickTime = currentTime
    }

    // 震动处理
    private fun triggerVibration() {
        if (vibrator.hasVibrator()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(
                    50,
                    VibrationEffect.DEFAULT_AMPLITUDE
                ))
            } else {
                @Suppress("DEPRECATION")
                vibrator.vibrate(50)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        gameView.pauseGame()
    }

    override fun onDestroy() {
        super.onDestroy()
        isThreadRunning = false
        dbHelper.close()
        vibrator.cancel()
    }
}